package com.ruoyi.project.system.house.house.controller;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.ZipAnAra.UnZipAnRar;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.qiniu.QiNiuUploadUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.AppBeanInjector;
import com.ruoyi.project.system.house.house.domain.House;
import com.ruoyi.project.system.house.house.enums.HouseDto;
import com.ruoyi.project.system.house.house.service.IHouseService;
import com.ruoyi.project.system.house.img.domain.HouseImg;
import com.ruoyi.project.system.house.img.service.IHouseImgService;
import com.ruoyi.project.system.house.orientation.domain.HouseOrientation;
import com.ruoyi.project.system.house.orientation.service.IHouseOrientationService;
import com.ruoyi.project.system.house.renovation.domain.HouseRenovation;
import com.ruoyi.project.system.house.renovation.service.IHouseRenovationService;
import com.ruoyi.project.system.house.type.domain.HouseType;
import com.ruoyi.project.system.house.type.service.IHouseTypeService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * 房源信息Controller
 * 
 * @author f_baisi
 * @date 2020-08-27
 */
@Controller
@RequestMapping("/system/house/house")
public class HouseController extends BaseController
{
    private String prefix = "system/house/house";

    @Autowired
    private IHouseService houseService;

    @Autowired
    private IHouseTypeService houseTypeService;

    @Autowired
    private IHouseRenovationService houseRenovationService;

    @Autowired
    private IHouseImgService houseImgService;

    @Autowired
    private IHouseOrientationService houseOrientationService;

    @RequiresPermissions("system/house:house:view")
    @GetMapping()
    public String house(ModelMap map)
    {
        map.put("renovationList",this.houseRenovationService.selectHouseRenovationList(null));
        map.put("typeList",this.houseTypeService.selectHouseTypeList(null));
        return prefix + "/house";
    }
    @RequiresPermissions("system/house:house:view")
    @GetMapping("/exmine")
    public String examin(ModelMap map)
    {
        map.put("renovationList",this.houseRenovationService.selectHouseRenovationList(null));
        map.put("typeList",this.houseTypeService.selectHouseTypeList(null));
        return prefix + "/exmine";
    }

    /**
     * 查询房源信息列表
     */
    @RequiresPermissions("system/house:house:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(House house)
    {
        startPage();
        List<HouseDto> list = houseService.selectHouseList(house);
        return getDataTable(list);
    }

    /**
     * 导出房源信息列表
     */
    @RequiresPermissions("system/house:house:export")
    @Log(title = "房源信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(House house)
    {
        List<HouseDto> list = houseService.selectHouseList(house);
        ExcelUtil<HouseDto> util = new ExcelUtil<HouseDto>(HouseDto.class);
        return util.exportExcel(list, "house");
    }

    /**
     * 新增房源信息
     */
    @GetMapping("/add")
    public String add(ModelMap map)
    {
        map.put("renovationList",this.houseRenovationService.selectHouseRenovationList(null));
        map.put("typeList",this.houseTypeService.selectHouseTypeList(null));
        map.put("orientationList",this.houseOrientationService.selectHouseOrientationList(null));
        return prefix + "/add";
    }

    /**
     * 新增保存房源信息
     */
    @RequiresPermissions("system/house:house:add")
    @Log(title = "房源信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(House house,String[] carImg0)
    {
    	house.setDeltag(0);
        //添加房源信息
        houseService.insertHouse(house);
        if(carImg0!=null){
            for (int j = 0; j <carImg0.length ; j++) {
                HouseImg houseImg = new HouseImg();
                houseImg.setHouseId(house.getId());
                houseImg.setUrl(carImg0[j]);
                this.houseImgService.insertHouseImg(houseImg);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改房源信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        HouseDto house = houseService.selectHouseById(id);
        HouseImg houseImg = new HouseImg();
        houseImg.setHouseId(id);
        house.setHouseImgs(this.houseImgService.selectHouseImgList(houseImg));
        mmap.put("house", house);
        mmap.put("renovationList",this.houseRenovationService.selectHouseRenovationList(null));
        mmap.put("typeList",this.houseTypeService.selectHouseTypeList(null));
        mmap.put("orientationList",this.houseOrientationService.selectHouseOrientationList(null));
        return prefix + "/edit";
    }
    /**
     * 修改房源信息
     */
    @GetMapping("/exmine/{id}")
    public String exmineEdit(@PathVariable("id") String id, ModelMap mmap)
    {
        HouseDto house = houseService.selectHouseById(id);
        HouseImg houseImg = new HouseImg();
        houseImg.setHouseId(id);
        house.setHouseImgs(this.houseImgService.selectHouseImgList(houseImg));
        mmap.put("house", house);
        mmap.put("renovationList",this.houseRenovationService.selectHouseRenovationList(null));
        mmap.put("typeList",this.houseTypeService.selectHouseTypeList(null));
        mmap.put("orientationList",this.houseOrientationService.selectHouseOrientationList(null));
        return prefix + "/exminehouse";
    }

    /**
     * 修改保存房源信息
     */
    @RequiresPermissions("system/house:house:edit")
    @Log(title = "房源信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @Transactional
    public AjaxResult editSave(House house,String[] carImg0)
    {
        //清除原本的图片信息
        this.houseImgService.deleteByHid(house.getId());
        if(carImg0!=null){
            for (int j = 0; j <carImg0.length ; j++) {
                HouseImg houseImg = new HouseImg();
                houseImg.setHouseId(house.getId());
                houseImg.setUrl(carImg0[j]);
                this.houseImgService.insertHouseImg(houseImg);
            }
        }
		HouseDto houseDto = this.houseService.selectHouseById(house.getId());
        if(!houseDto.getStatus().equals(house.getStatus())){
        	house.setCreated(DateUtils.getNowDate());
		}
		return toAjax(houseService.updateHouse(house));
    }

    /**
     * 删除房源信息
     */
    @RequiresPermissions("system/house:house:remove")
    @Log(title = "房源信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(houseService.deleteHouseByIds(ids));
    }


    @PostMapping("/importData")
    @Transactional
    @ResponseBody
    public AjaxResult importData(MultipartFile file){

        String s = RuoYiConfig.getUploadPath() + "/zip/"+file.getOriginalFilename();
        File desc = new File(s);
        try {
            // 判断文件目录是否存在
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
            if (!desc.exists())
            {
                desc.createNewFile();
            }
            file.transferTo(desc);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //解压压缩文件
        //判断是zip 还是 rar
        String name = desc.getName();
        String outp = RuoYiConfig.getUploadPath() + "/zip/"+name.replace(".zip","");
        String outpath = outp+"/";
        try {
            if(name.endsWith(".zip")){
//                outpath=s.replace(".zip","")+"\\";
                UnZipAnRar.unZip(desc,outpath);
            }
            if(name.endsWith(".ara")){
//                outpath=s.replace(".ara","")+"\\";
                UnZipAnRar.unRar(desc,outpath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //读取文件夹下的文件列表
        File outfile = new File(outpath);
        String[] files = outfile.list();
        File temp = null;
        for(int i=0;i<files.length;i++){
            // 判断给的oldpath最后有没有带下级符号(就是\\没有的话 就给他加上 )
            if (outpath.endsWith(File.separator)) {
                temp = new File(outpath + files[i]);
            } else {
                temp = new File(outpath + File.separator + files[i]);
            }
            // 如果是子文件夹
            if (temp.isDirectory()) {
                //通过文件夹名称查找相关房源
                List<House> houseList = this.houseService.findByFile(files[i]);
                for (int j = 0; j < houseList.size(); j++) {
                    //清除房源原本相关图片
                    this.houseImgService.deleteByHid(houseList.get(j).getId());
                    //添加文件夹下的图片
                    String[] imgList = temp.list();
                    for (int k = 0; k <imgList.length; k++) {
                        File imgFile = new File(temp + File.separator + imgList[k]);
                        String fileName = FileUploadUtils.extractFilename(imgFile);
                        // 上传并返回新文件名称
                        AppBeanInjector.qiniuUploadUtil.upload(FileUploadUtils.File2byte(imgFile),fileName);
                        String url = QiNiuUploadUtil.getBaseUrl() + fileName;
                        HouseImg houseImg = new HouseImg();
                        houseImg.setUrl(url);
                        houseImg.setHouseId(houseList.get(j).getId());
                        this.houseImgService.insertHouseImg(houseImg);
                    }
                }
            }
        }
        //删除解压后的文件夹
        FileUploadUtils.deleteDirectory(outp);
        //删除压缩包
        FileUploadUtils.delete(s);

        return AjaxResult.success("ok");
    }


	@PostMapping("/importExcel")
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@ResponseBody
	@Transactional
	public R orderImport(MultipartFile file){
		if(file!= null) {
			String userExcelFileName = file.getOriginalFilename();
			//判断是否是Excel文件
			if(userExcelFileName.matches("^.+\\.(?i)((xls)|(xlsx))$"))
			{
				importExcel(file, userExcelFileName);
				return R.ok();
			}
			return R.error("文件类型错误");
		}
		return R.error("请选择文件");
	}


	public void importExcel(MultipartFile file, String excelFileName) {
		//1.创建输入流
		try {
			//FileInputStream inputStream = new FileInputStream(file);
			//boolean is03Excel = excelFileName.matches("^.+\\.(?i)(xls)$");
			//1.读取工作簿
			boolean is03Excel = excelFileName.matches("^.+\\.(?i)(xls)$");
			Workbook workbook = is03Excel?new HSSFWorkbook(file.getInputStream()):new XSSFWorkbook(file.getInputStream());
			//Workbook workbook = new HSSFWorkbook(file.getInputStream());
			//2.读取工作表
			Sheet sheet = workbook.getSheetAt(0);
			//3.读取行
			//判断行数大于一,是因为数据从第二行开始插入

			if(sheet.getPhysicalNumberOfRows() > 1) {
				//跳过前一行
				for(int k=1;k<sheet.getPhysicalNumberOfRows();k++ ) {
					House house = new House();
					//读取单元格
					Row row0 = sheet.getRow(k);
					//名称
					Cell cell0 = row0.getCell(0);
					cell0.setCellType(Cell.CELL_TYPE_STRING);
					String name =cell0.getStringCellValue().replace("\t","").trim();
					house.setName(name);
					//装修
					Cell cell1 = row0.getCell(1);
					cell1.setCellType(Cell.CELL_TYPE_STRING);
					String renovation = cell1.getStringCellValue().replace("\t","").trim();
					//查询装修对应的ID
					HouseRenovation houseRenovation = this.houseRenovationService.findByName(renovation);
					//如果不存在 则新建一个
					if(houseRenovation==null){
						houseRenovation = new HouseRenovation();
						houseRenovation.setName(renovation);
						houseRenovation.setSort(1);
						this.houseRenovationService.insertHouseRenovation(houseRenovation);
					}
					house.setRenovationId(houseRenovation.getId());
					//住宅类型
					Cell cell2 = row0.getCell(2);
					cell2.setCellType(Cell.CELL_TYPE_STRING);
					String type = cell2.getStringCellValue().replace("\t","").trim();
					//查询住宅对应的ID
					HouseType houseType = this.houseTypeService.findByName(type);
					//如果不存在 则新建一个
					if(houseType==null){
						houseType = new HouseType();
						houseType.setName(type);
						houseType.setSort(1);
						this.houseTypeService.insertHouseType(houseType);
					}
					house.setTypeId(houseType.getId());
					//朝向
					Cell cell3 = row0.getCell(3);
					cell3.setCellType(Cell.CELL_TYPE_STRING);
					String orientation = cell3.getStringCellValue().replace("\t","").trim();
					//查询朝向对应的ID
					HouseOrientation houseOrientation = this.houseOrientationService.findByName(orientation);
					//如果不存在 则新建一个
					if(houseOrientation==null){
						houseOrientation = new HouseOrientation();
						houseOrientation.setName(orientation);
						houseOrientation.setSort(1);
						this.houseOrientationService.insertHouseOrientation(houseOrientation);
					}
					house.setOrientationId(houseOrientation.getId());


					//年代
					Cell cell4 = row0.getCell(4);
					cell4.setCellType(Cell.CELL_TYPE_STRING);
					String years =cell4.getStringCellValue().replace("\t","").trim();
					house.setYears(years);

					//地址
					Cell cell5 = row0.getCell(5);
					cell5.setCellType(Cell.CELL_TYPE_STRING);
					String address =cell5.getStringCellValue().replace("\t","").trim();
					house.setAddress(address);

					//描述
					Cell cell6 = row0.getCell(6);
					cell6.setCellType(Cell.CELL_TYPE_STRING);
					String notes =cell6.getStringCellValue().replace("\t","").trim();
					house.setNotes(notes);

					//售价
					Cell cell7 = row0.getCell(7);
					BigDecimal price= new BigDecimal(Double.valueOf(cell7.getNumericCellValue()).intValue());
					house.setPrice(price);

					//单价
					Cell cell8 = row0.getCell(8);
					BigDecimal onePrice= new BigDecimal(Double.valueOf(cell8.getNumericCellValue()).intValue());
					house.setPriceOne(onePrice);

					//户型-室
					Cell cell9 = row0.getCell(9);
					Integer room= Double.valueOf(cell9.getNumericCellValue()).intValue();
					house.setHouseRoom(room);

					//户型-厅
					Cell cell10 = row0.getCell(10);
					Integer living= Double.valueOf(cell10.getNumericCellValue()).intValue();
					house.setHouseLivingRoom(living);

					//户型-卫
					Cell cell11 = row0.getCell(11);
					Integer toilet= Double.valueOf(cell11.getNumericCellValue()).intValue();
					house.setHouseToilet(toilet);

					//面积
					Cell cell12 = row0.getCell(12);
					Integer area= Double.valueOf(cell12.getNumericCellValue()).intValue();
					house.setArea(area);

					//楼层
					Cell cell13 = row0.getCell(13);
					Integer floor= Double.valueOf(cell13.getNumericCellValue()).intValue();
					house.setFloor(floor);

					//总楼层
					Cell cell14 = row0.getCell(14);
					Integer maxFloor= Double.valueOf(cell14.getNumericCellValue()).intValue();
					house.setFloorMax(maxFloor);

					//标签
					Cell cell15 = row0.getCell(15);
					cell15.setCellType(Cell.CELL_TYPE_STRING);
					String tag =cell15.getStringCellValue().replace("\t","").trim();
					house.setTag(tag);

					//排序
					Cell cell16 = row0.getCell(16);
					Integer sort= Double.valueOf(cell16.getNumericCellValue()).intValue();
					house.setSort(sort);

					//文件名称
					Cell cell17 = row0.getCell(17);
					cell17.setCellType(Cell.CELL_TYPE_STRING);
					String fileName =cell17.getStringCellValue().replace("\t","").trim();
					house.setFile(fileName);

					//状态
					Cell cell18 = row0.getCell(18);
					Integer status= Double.valueOf(cell18.getNumericCellValue()).intValue();
					house.setStatus(status);

					//是否独家
					Cell cell19 = row0.getCell(19);
					Integer sole= Double.valueOf(cell19.getNumericCellValue()).intValue();
					house.setSole(sole);

					//是否推荐
					Cell cell20 = row0.getCell(20);
					Integer recommend= Double.valueOf(cell20.getNumericCellValue()).intValue();
					house.setIsRecommend(recommend);

					//类型
					Cell cell21 = row0.getCell(21);
					Integer t= Double.valueOf(cell21.getNumericCellValue()).intValue();
					house.setType(t);

					//描述
					Cell cell22 = row0.getCell(22);
					cell22.setCellType(Cell.CELL_TYPE_STRING);
					String traffic =cell22.getStringCellValue().replace("\t","").trim();
					house.setTraffic(traffic);
					this.houseService.insertHouse(house);


				}
			}
			workbook.close();
			//inputStream.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	@RequiresPermissions("system:dealer:view")
	@GetMapping("/map")
	public String map()
	{
		return prefix + "/map";
	}

}
